<!-- 角色编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="700"
    v-model="visible"
    :title="actionConfigs[action].title"
    @open="handleOpen"
    @close="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="currentRules"
      label-width="80px"
      @submit.prevent=""
    >
      <el-row :gutter="8">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input
              clearable
              :maxlength="255"
              v-model="form.title"
              placeholder="请输入标题"
            />
          </el-form-item>
          <el-form-item label="文章分类" prop="category_id">
            <dict-type-data
              code="information_category"
              v-model="form.category_id"
              placeholder="请选择文章分类"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <dict-data
              code="status"
              v-model="form.status"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input
              show-word-limit
              maxlength="1000"
              :rows="4"
              type="textarea"
              v-model="form.desc"
              placeholder="请输入描述"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关键词" prop="meta_keywords">
            <el-input
              clearable
              :maxlength="255"
              v-model="form.meta_keywords"
              placeholder="请输入关键词"
            />
          </el-form-item>
          <el-form-item label="封面图" prop="cover">
            <image-upload
              ref="imagesUploadRef"
              :limit="1"
              v-model="form.cover"
            />
          </el-form-item>

          <el-form-item label="排序" prop="sort_number">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.sort_number"
              placeholder="请输入排序"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="文章内容" prop="content">
            <tinymce-editor
              ref="editorRef"
              :init="config"
              v-model="form.content"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ actionConfigs[action].button }}
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import {
  addInformation,
  updateInformation,
  getInformation,
} from "@/api/base/information";
import { ref, reactive, nextTick } from "vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import TinymceEditor from "@/components/TinymceEditor/index.vue";

import { useFormEdit } from "@/hooks/useFormEdit";
const props = defineProps({
  /** 修改回显的数据 */
  data: Object,
  action: {
    type: String,
    default: "edit",
    validator: (value) =>
      ["add", "edit", "audit", "push", "view"].includes(value),
  },
});
/** 现场照片上传组件 */
const imagesUploadRef = ref(null);
const emit = defineEmits(["update:modelValue", "done", "open"]);
/** 编辑器配置 */
const config = ref({
  height: 200,
});
const actionConfigs = {
  add: {
    title: "新增文章",
    button: "新增",
    api: addInformation,
    showFields: ["title", "cover"],
    disabledFields: [],
    rules: {
      title: [
        {
          required: true,
          message: "请输入标题",
          type: "string",
          trigger: "blur",
        },
      ],
      cover: [
        {
          required: false,
          message: "请上传封面图",
          type: "string",
          trigger: "change",
        },
        {
          type: "string",
          trigger: "change",
          validator: (_rule, _value, callback) => {
            if (!imagesUploadRef.value?.isDone?.()) {
              return callback(new Error("封面图还未上传完毕"));
            }
            callback();
          },
        },
      ],
    },
    beforeOpen: async ({ type, formData }) => {
      // 打开前的操作，可以修改表单数据
      console.log("打开前的操作", formData);
      return { type, formData }; // 必须返回处理后的表单数据
    },
    beforeSubmit: async ({ type, formData }) => {
      // 提交前的操作，可以修改表单数据
      console.log("提交数据:", formData);
      // if (!formData.requiredField) {
      // return Promise.reject(new Error("缺少必填字段")); // 返回rejected Promise中断流程
      // }
      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  edit: {
    title: "修改文章",
    button: "保存",
    api: updateInformation, // 补充edit的API
    showFields: ["title", "cover"],
    disabledFields: [],
    rules: {
      title: [
        {
          required: true,
          message: "请输入标题",
          type: "string",
          trigger: "blur",
        },
      ],
      cover: [
        {
          required: false,
          message: "请上传封面图",
          type: "string",
          trigger: "change",
        },
        {
          type: "string",
          trigger: "change",
          validator: (_rule, _value, callback) => {
            if (!imagesUploadRef.value?.isDone?.()) {
              return callback(new Error("封面图还未上传完毕"));
            }
            callback();
          },
        },
      ],
    },
    beforeSubmit: async ({ type, formData }) => {
      // 提交前的操作，可以修改表单数据
      console.log("提交数据:", formData);
      // // 添加实际验证逻辑
      // if (
      //   !formData.dict_data_name ||
      //   !formData.dict_data_code ||
      //   !formData.sort_number
      // ) {
      // return Promise.reject(new Error("请填写所有必填字段"));
      // }
      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  view: {
    title: "查看文章数据",
    button: "确定",
    // api: showDictionaryData, // 补充view的API
    showFields: ["title", "cover", "comments"],
    disabledFields: [],
    rules: {},
  },
};

const {
  form,
  formRef,
  visible,
  loading,
  handleOpen,
  handleSubmit,
  currentRules,
  handleCancel,
} = useFormEdit(props, emit, {
  actionConfigs,
  formFields: {
    id: void 0,
    title: "",
    cover: "",
    category_id: "",
    desc: "",
    content: "",
    meta_keywords: "",
    status: 1,
    sort_number: 0,
  },
  detailApi: getInformation,
  idField: "id",
});
</script>
